package com.bite.forum.controller;

import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.config.AppConfig;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.User;
import com.bite.forum.services.IUserService;
import com.bite.forum.utils.MD5Util;
import com.bite.forum.utils.StringUtil;
import com.bite.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService iuserService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @Operation(description = "用户注册")
    @RequestMapping("/register")
    public AppResult register(@Schema(description = "用户名") @RequestParam("username") @NotNull String username,
                              @Schema(description = "昵称") @RequestParam("nickname") @NotNull String nickname,
                              @Schema(description = "密码") @RequestParam("password") @NotNull String password,
                              @Schema(description = "确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        /*if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname) ||
           StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)){
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }*/

        if(!password.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        User user  = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);

        if(user.getUsername().length() > 20){
            log.info(ResultCode.FAILED_USERNAME_TOO_LONG.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USERNAME_TOO_LONG));
        }

        if(user.getPassword().length() > 18){
            log.info(ResultCode.FAILED_PASSWORD_TOO_LONG.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PASSWORD_TOO_LONG));
        }
        //盐值
        String salt = UUIDUtil.UUID_32();
        user.setPassword(MD5Util.md5Salt(password,salt));
        user.setSalt(salt);

        iuserService.craeteNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 登录密码
     * @return 登录成功与否
     */
    @Operation(description = "用户登录")
    @RequestMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @Schema(description = "用户名") @RequestParam("username") @NotNull String username,
                           @Schema(description = "密码") @RequestParam("password") @NotNull String password){
        User user = iuserService.login(username, password);
        if(user == null){
            log.info(ResultCode.FAILED_LOGIN.toString());
            return AppResult.fail(ResultCode.FAILED_LOGIN);
        }

        HttpSession session = request.getSession();
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success();
    }

    /**
     * 根据用户id查询用户信息
     * @param id 用户id
     * @return 用户信息
     */
    @Operation(description = "根据用户名查询用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @Schema(description = "用户Id") @RequestParam(value = "id", required = false) Long id) {
        // 定义返回的User对象
        User user = null;
        // 根据Id的值判断User对象的获取方式
        if (id == null) {
            // 1. 如果id为空，从session中获取当前登录的用户信息
            HttpSession session = request.getSession(false);
            // 从session中获取当前登录的用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            // 2. 如果id不为空，从数据库中按Id查询出用户信息
            user = iuserService.selectById(id);
        }
        // 判断用户对象是否为空
        if (user == null) {
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 返回正常的结果
        return AppResult.success(user);
    }

    @Operation(description = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session != null){
            log.info("退出登录成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @Operation(description = "修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
           //@SessionAttribute(AppConfig.USER_SESSION) User user,
           @Schema(description = "用户名") @RequestParam(value = "username", required = false) String username,
           @Schema(description = "用户昵称") @RequestParam(value = "nickname", required = false) String nickname,
           @Schema(description = "用户性别") @RequestParam(value = "gender", required = false) Byte gender,
           @Schema(description = "用户邮箱") @RequestParam(value = "email", required = false) String email,
           @Schema(description = "用户电话") @RequestParam(value = "phoneNum", required = false) String phoneNum,
           @Schema(description = "用户简介") @RequestParam(value = "remark", required = false) String remark){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
            && gender == null && StringUtil.isEmpty(email)
            && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark)){
            return AppResult.fail("请输入有效用户信息");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());

        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        iuserService.modifyInfo(updateUser);

        user = iuserService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success();
    }

    @Operation(description = "修改密码信息")
    @PostMapping("/modifyPassword")
    public AppResult modifyPassword(HttpServletRequest request,
           //@SessionAttribute(AppConfig.USER_SESSION) User user,
           @Schema(description = "旧密码") @RequestParam(value = "oldPassword") @NotNull String oldPassword,
           @Schema(description = "新密码") @RequestParam(value = "newPassword") @NotNull String newPassword,
           @Schema(description = "确认新密码") @RequestParam(value = "passwordRepeat") @NotNull String passwordRepeat) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(!newPassword.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        iuserService.modifyPassword(user.getId(), newPassword, oldPassword);


        if(session != null){
            session.invalidate();
        }
        return AppResult.success();
    }
}
